<template>
  <div class="flex-1 page_contain">
    <div class="app-container">
      <!-- 搜索框 -->
      <div class="search-container">
        <el-form :model="searchParam" :inline="true" label-width="72px">
          <el-form-item label="工序">
            <el-select
              v-model="searchParam.processCode"
              placeholder="请选择工序"
              clearable
              filterable
              @change="processChange"
            >
              <el-option
                v-for="item in processCodeList"
                :key="item.processCode"
                :label="item.processName"
                :value="item.processCode"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="设备">
            <el-select
              v-model="searchParam.deviceCode"
              placeholder="请选择设备"
              clearable
              filterable
              @change="equipChange"
            >
              <el-option
                v-for="item in equipList"
                :key="item.equipCode"
                :label="item.equipName"
                :value="item.equipCode"
              />
            </el-select>
          </el-form-item>

          <!-- <el-form-item label="参数类型">
            <el-radio-group v-model="searchParam.paramType">
              <el-radio-button label="2">工艺加工</el-radio-button>
              <el-radio-button label="3">工艺过程</el-radio-button>
            </el-radio-group>
          </el-form-item> -->
          <el-form-item label="参数类型">
            <el-select
              v-model="searchParam.processDataType"
              placeholder="请选择参数类型"
              clearable
              filterable
              @change="processTypeChange"
            >
              <el-option label="工艺加工参数" value="2" />
              <el-option label="工艺过程参数" value="3" />
            </el-select>
          </el-form-item>

          <el-form-item label="工艺参数">
            <el-select
              v-model="searchParam.parameterName"
              placeholder="请选择工艺参数"
              clearable
              filterable
              :disabled="!searchParam.deviceCode"
              @change="processParameterChange"
            >
              <el-option
                v-for="(item, index) in collectParamList"
                :key="index"
                :label="item.parameterDesc"
                :value="item.parameterName"
              />
              <!-- <el-option
                v-for="(item, index) in collectParamList"
                :key="index"
                :label="item.parameterName"
                :value="item.id"
              /> -->
            </el-select>
          </el-form-item>

          <el-form-item label="产品型号">
            <el-select
              v-model="searchParam.productModel"
              placeholder="请选择产品型号"
              clearable
              filterable
              @change="productChange"
            >
              <el-option
                v-for="item in productList"
                :key="item.productModel"
                :label="item.productModel"
                :value="item.productModel"
              />
            </el-select>
          </el-form-item>

          <!-- <el-form-item label="参数类型">
            <el-select
              v-model="searchParam.processDataType"
              placeholder="请选择参数类型"
              clearable
              filterable
              @change="processTypeChange"
            >
              <el-option label="工艺加工参数" value="2" />
              <el-option label="工艺过程参数" value="3" />
            </el-select>
          </el-form-item> -->
          <el-form-item label="监控结果">
            <el-select
              v-model="searchParam.monitorResult"
              placeholder="请选择监控结果"
              clearable
              filterable
            >
              <el-option label="全部" value="" />
              <el-option label="未超控制范围" value="1" />
              <el-option label="超过控制范围" value="2" />
            </el-select>
          </el-form-item>
          <el-form-item label="程序名">
            <el-input
              v-model="searchParam.programName"
              placeholder="请输入程序名"
              clearable
              @keyup.enter="handleSearch"
            />
          </el-form-item>
          <el-form-item label="监控时间">
            <el-date-picker
              v-model="searchParam.collectionTimeSearch"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
              @change="getPointTime"
            />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <i-ep-search />
              搜索
            </el-button>
            <el-button @click="handleReset">
              <i-ep-refresh />
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      <!-- 列表 -->
      <el-tabs
        type="border-card"
        @tab-click="tabClickHandle"
        v-model="activeTabs"
      >
        <el-tab-pane label="详细数据"
          ><el-table
            ref="dataTableRef"
            v-loading="loading"
            :data="tableData"
            highlight-current-row
            border
            @selection-change="handleSelectionChange"
          >
            <el-table-column
              label="工序"
              prop="processCode"
              fixed="left"
              min-width="120"
              align="center"
              show-overflow-tooltip
            />
            <el-table-column
              label="设备编号"
              prop="deviceCode"
              min-width="120"
              align="center"
              fixed="left"
              show-overflow-tooltip
            />
            <el-table-column
              label="设备名称"
              prop="deviceName"
              min-width="150"
              align="center"
              show-overflow-tooltip
            />
            <el-table-column
              label="产品型号"
              prop="productModel"
              align="center"
              min-width="140"
              show-overflow-tooltip
            />
            <el-table-column
              label="程序名"
              prop="programName"
              min-width="120"
              align="center"
              show-overflow-tooltip
            />
            <el-table-column
              label="采集时间"
              prop="collectionTime"
              min-width="160"
              align="center"
              show-overflow-tooltip
            />
            <el-table-column
              label="参数类型"
              prop="processDataType"
              min-width="120"
              align="center"
              show-overflow-tooltip
            >
              <template #default="scope">
                <el-tag v-if="scope.row.processDataType == 2">加工参数</el-tag>
                <el-tag type="success" v-if="scope.row.processDataType == 3"
                  >过程参数</el-tag
                >
              </template>
            </el-table-column>
            <el-table-column
              label="参数描述"
              prop="parameterDesc"
              min-width="170"
              align="center"
              show-overflow-tooltip
            />

            <el-table-column
              label="采集值"
              prop="parameterValue"
              min-width="120"
              align="right"
              show-overflow-tooltip
            />
            <el-table-column
              label="参考值"
              prop="referenceValue"
              min-width="120"
              align="right"
              show-overflow-tooltip
            />
            <el-table-column
              label="控制范围"
              min-width="160"
              align="right"
              show-overflow-tooltip
            >
              <template #default="scope">
                <span
                  v-if="scope.row.lowerLimitValue == scope.row.upperLimitValue"
                  >{{ scope.row.lowerLimitValue ?? "" }}</span
                >
                <span v-else
                  >{{ scope.row.lowerLimitValue }} -
                  {{ scope.row.upperLimitValue }}</span
                >
              </template>
            </el-table-column>
            <el-table-column label="监控结果" align="center" min-width="150">
              <template #default="scope">
                <el-tag v-if="scope.row.monitorResult == 1" type="warning"
                  >变更未超控制范围</el-tag
                >
                <el-tag v-if="scope.row.monitorResult == 2" type="danger"
                  >变更超过控制范围</el-tag
                >
                <el-tag
                  v-if="
                    scope.row.monitorResult != 2 && scope.row.monitorResult != 1
                  "
                  type="success"
                  >正常</el-tag
                >
              </template>
            </el-table-column>
            <!-- 暂时没有工位字段 -->
            <!-- <el-table-column
            label="工位"
            prop="remarks"
            min-width="150"
            align="center"
            show-overflow-tooltip
          /> -->
            <el-table-column
              label="工单"
              prop="orderNo"
              min-width="150"
              align="center"
              show-overflow-tooltip
            />
          </el-table>

          <el-pagination
            :background="true"
            :current-page="pageable.pageNum"
            :page-size="pageable.pageSize"
            :page-sizes="[10, 25, 50, 100]"
            :total="pageable.total"
            layout="total, sizes, prev, pager, next, jumper"
            class="mt-[20px]"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        /></el-tab-pane>
        <el-tab-pane label="趋势图">
          <div
            v-if="singleLoading"
            v-loading="true"
            class="w-full h-[400px]"
          ></div>
          <!-- 数据为空 -->
          <div v-if="!singleLoading && !singleData">
            <el-empty description="暂无数据" />
          </div>
          <div v-if="singleData">
            <psmParamLineChart
              key="1"
              id="1"
              :showName="true"
              :seriesData="singleData"
            />
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script lang="ts" setup>
import request from "@/utils/request";
import { useTable } from "@/utils/useTable";
import router from "@/router";
import dayjs from "dayjs";
import { getMdmproductinfosApi1 } from "@/utils/commonData";
import psmParamLineChart from "@/views/psm/psmParamQuery/components/psmParamLineChart.vue";
// import { getSingleDataMock } from "@/views/pcm/pcmMonitoring/index";

defineOptions({
  name: "PSMPSMPARAMQUERY",
  inheritAttrs: false,
});

function handleReset() {
  router.go(0);
}

const activeTabs = ref("0");
function handleSearch() {
  if (activeTabs.value == "1") {
    getSingleData();
    search();
  } else {
    if (!searchParam.value.collectionTimeStart) {
      ElMessage.error("请选择监控时间");
      return;
    }
    let startTime = dayjs(searchParam.value.collectionTimeStart); // 开始时间
    let endTime = dayjs(searchParam.value.collectionTimeEnd); // 结束时间
    if (endTime.diff(startTime, "hour") > 24 * 7) {
      ElMessage.error("监控时间不能超过七天");
      return;
    }
    search();
  }
}

// 请求参数
const requestApi = "/dmpDosPcm/psmprocessdata/queryByPage";

// 是否需要分页
const pagination = true;

const initParam = {};

// 初始化搜索参数数据
const searchParamInit = {
  processCode: "", // 工序编号
  processId: "", // 工序id
  deviceCode: "", // 设备编号
  deviceId: "", // 设备id
  processDataType: "", // 参数类别
  parameterName: "", // 工艺参数
  parameterDesc: "", // 工艺描述
  // productId: "", // 产品型号
  monitorResult: "", // 监控结果
  programName: "", // 程序名
  productModel: "", // 产品型号
  // 监控时间
  collectionTimeStart: dayjs(Date.now())
    .subtract(7, "day")
    .format("YYYY-MM-DD"),
  collectionTimeEnd: dayjs(Date.now()).format("YYYY-MM-DD"),
  collectionTimeSearch: [
    dayjs(Date.now()).subtract(7, "day").format("YYYY-MM-DD"),
    dayjs().format("YYYY-MM-DD"),
  ],
};

const deleteParam = {
  api: "/system/sysRole/delete",
  data: {},
};

// 如果初始化表格需要排序=》const initParam = reactive({sort:''});
// 监听页面 initParam 改化，重新获取表格数据
// watch(() => initParam, getTableList, { deep: true });

// 数据请求错误后处理
function requestError() {}

// 数据请求错误后处理
// function dataCallBack() {}   //需要处理
const dataCallBack = ref(undefined); //无需二次数据处理&不传赞数也行

// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  loading,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack.value,
  requestError,
  deleteParam
);

// 获取产品型号列表
const productList = ref<any>([]);
async function getProductList() {
  const list: any =
    (await getMdmproductinfosApi1({ deviceId: searchParam.value.deviceId })) ||
    [];
  productList.value = [...list];
}
function productChange(id: string) {
  if (id) {
    const current: any =
      productList.value?.filter((e: any) => e.id === id)[0] ?? {};
    searchParam.value.productCode = current.productCode || "";
  } else {
    searchParam.value.productCode = "";
  }
}

// 获取工序列表
const processCodeList: any = ref([]);
async function getProcessCodeList() {
  const { data } = await request({
    url: `/mdm/mdmprocess/getList`,
    method: "post",
    data: {},
  });
  processCodeList.value = data;
}
function processChange(code: string) {
  searchParam.value.deviceCode = "";
  searchParam.value.parameterName = "";
  searchParam.value.parameterDesc = "";
  searchParam.value.productModel = "";
  if (code) {
    const current: any =
      processCodeList.value?.filter((e: any) => e.processCode === code)[0] ??
      {};
    searchParam.value.processId = current.id || "";
    getEquipList();
  } else {
    equipList.value = [];
    searchParam.value.processId = "";
    getEquipList();
  }
}

// 通过工序查询设备列表
const equipList = ref(<any>[]);
async function getEquipList(id?: string) {
  const res: any = await request({
    // url: "/iotadmin/scaequipinfo/getlist",
    url: "/dmpDosPcm/equipmentInfo/getList",
    method: "post",
    data: {
      processCode: searchParam.value.processCode,
      processId: searchParam.value.processId,
    },
  });
  if (res.code === 200) {
    equipList.value = res.data;
  }
}
function equipChange(id: string) {
  searchParam.value.parameterName = "";
  searchParam.value.parameterDesc = "";
  searchParam.value.productModel = "";
  collectParamList.value = [];
  if (id) {
    const current: any =
      equipList.value?.filter((e: any) => e.equipCode === id)[0] ?? {};
    searchParam.value.deviceId = current.equipId || "";
    getCollectParamList();
    getProductList();
  } else {
    searchParam.value.deviceId = "";
    getProductList();
  }
}

function processTypeChange(id: string) {
  searchParam.value.parameterDesc = "";
  searchParam.value.parameterName = "";

  collectParamList.value = [];
  if (id) {
    getCollectParamList();
  } else {
    getCollectParamList();
  }
}

function processParameterChange(name: string) {
  if (name) {
    const current: any =
      collectParamList.value?.filter((e: any) => e.parameterName === name)[0] ??
      {};
    searchParam.value.parameterDesc = current.parameterDesc || "";
  } else {
    searchParam.value.parameterDesc = "";
  }
}

const collectParamList = ref(<any>[]);
async function getCollectParamList(id?: string) {
  const res: any = await request({
    url: "/iotadmin/scaequipcollectionparam/getProcessParamList",
    method: "post",
    data: {
      paramType: searchParam.value.processDataType,
      relationId: searchParam.value.deviceId,
    },
  });
  if (res.code === 200) {
    collectParamList.value = res.data || [];
  }
}

// 更新创建时间
function getPointTime(data: any) {
  if (data) {
    searchParam.value.collectionTimeStart = data[0];
    searchParam.value.collectionTimeEnd = data[1];
  } else {
    searchParam.value.collectionTimeStart = "";
    searchParam.value.collectionTimeEnd = "";
  }
}

// tab点击事件
function tabClickHandle(e) {
  if (e.index == 1) {
    getSingleData();
  }
}

// 获取单值图数据
const singleLoading = ref(false);
const singleData = ref<any>(null);
async function getSingleData() {
  if (!searchParam.value.deviceId) {
    ElMessage.error("请先选择设备");
    return;
  }
  if (!searchParam.value.parameterName) {
    ElMessage.error("请先选择工艺参数");
    return;
  }
  if (!searchParam.value.collectionTimeStart) {
    ElMessage.error("请选择监控时间且不能超过七天");
    return;
  }
  let startTime = dayjs(searchParam.value.collectionTimeStart); // 开始时间
  let endTime = dayjs(searchParam.value.collectionTimeEnd); // 结束时间
  if (endTime.diff(startTime, "hour") > 24 * 7) {
    ElMessage.error("请选择监控时间且不能超过七天");
    return;
  }
  if (!searchParam.value.productModel) {
    ElMessage.warning("请选择产品型号");
    return;
  }
  // if (!searchParam.value.programName) {
  //   ElMessage.warning("请填写程序名");
  //   return;
  // }
  singleData.value = null;
  singleLoading.value = true;
  const { data }: any = await request({
    url: "/dmpDosPcm/psmprocessdata/curve",
    method: "post",
    data: toRaw(searchParam.value),
  })
    .finally(() => {
      singleLoading.value = false;
    })
    .catch((e) => {});
  singleData.value = {
    ...data,
    paramName: searchParam.value.parameterDesc,
  };

  // 模拟
  // singleData.value = {};
  // singleLoading.value = true;
  // setTimeout(() => {
  //   singleData.value = getSingleDataMock(100);
  //   console.log("singleData.value", singleData.value);
  //   singleLoading.value = false;
  // }, 1000);
}

onMounted(() => {
  getEquipList();
  getProcessCodeList();
  // 获取产品型号列表
  getProductList();
  getTableList();
});
</script>

<style lang="scss" scoped>
:deep(.el-tabs--border-card) {
  box-shadow: 0px 0px 12px rgba(3, 8, 72, 0.08);
  border: none;
}
</style>
